package cn.edu.zstu.qingzhu.qingzhushop.controller.admin;

import cn.edu.zstu.qingzhu.qingzhushop.controller.BaseRestController;
import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import cn.edu.zstu.qingzhu.qingzhushop.entity.ShoppingCart;
import cn.edu.zstu.qingzhu.qingzhushop.service.IGoodsService;
import cn.edu.zstu.qingzhu.qingzhushop.service.IShoppingCartService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

@RestController
@RequestMapping("/admin/shoppingCart")
@Api(tags = "用户购物车管理接口")
@CrossOrigin(origins={"*"}, methods={RequestMethod.GET, RequestMethod.POST})
public class ShoppingCartManagerController extends BaseRestController<IShoppingCartService, ShoppingCart,Integer> {

    @Autowired
    IShoppingCartService iShoppingCartService;

    @Autowired
    IGoodsService iGoodsService;

    //获取所有购物车
    @GetMapping("/list")
    @ResponseBody
    public ResponseBean getAllCarts(){
        List<ShoppingCart> shoppingCartList = iShoppingCartService.list();
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (ShoppingCart shopcart: shoppingCartList) {
            shopcart.setGoods(iGoodsService.selectByGoodsId(shopcart.getGoodsId()));
            //shopcart.setStr_gmtCreate(sdf.format(shopcart.getGmtCreate()));
            //shopcart.getGood().setCreateTime(shopcart.getGood().getCreateTime());
        }
        return ResponseBean.success("carts", shoppingCartList);
    }

    //获取某用户的所有购物车
    @PostMapping("/getShoppingCartOfUser")
    @ResponseBody
    public ResponseBean getCartsOfUser(@RequestParam("userId") Integer userId){
        List<ShoppingCart> shoppingCartList = iShoppingCartService.selectByUserId(userId);
        for (ShoppingCart cart: shoppingCartList) {
            cart.setGoods(iGoodsService.selectByGoodsId(cart.getGoodsId()));
        }
        return ResponseBean.success("carts", shoppingCartList);
    }

    //加入购物车
    @PostMapping("/addGoods")
    @ResponseBody
    public ResponseBean addCart(@RequestBody ShoppingCart shoppingCart){
        //System.out.println(shoppingCart.getUserId());
        System.out.println(shoppingCart.getGoodsNum());
        //System.out.println(shoppingCart.getTotalPrice());
        System.out.println(shoppingCart.getGoodsId());
        //Goods good = goodsService.selectByGoodsId(shoppingCart.getGoodsId());
        //shoppingCart.setTotalPrice((double)good.getGoodsPrice()*shoppingCart.getGoodsNum());
        if(iShoppingCartService.save(shoppingCart)){
            return ResponseBean.success();
        }else{
            return ResponseBean.error();
        }
    }
}